package com.kim.rssreader.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import com.kim.rssreader.db.DBDAO;
import com.kim.rssreader.domain.RssContent;
import com.kim.rssreader.utils.NetUtil.NetProcessComplete;

/**
 * 数据抓取线程
 * 
 * @author KimHuang
 * 
 */
public class DataFetchService {

	// 避免同一篇文章重复抓取
	static HashMap<String, String> fetechCache = new HashMap<String, String>();

	public static String fetchAndPersistant(final String url,
			final DBDAO dbdao, final String columnFlagStarter,
			final String columnFlagEnd,
			final DataFetchCallback dataFetchCallback) {

		// 判断本地是否已缓存url对应的数据
		RssContent content = dbdao.getRssContentEntityByUrl(url);

		if (content != null && !"".equals(content.rssContent)) {
			// 回调接口
			dataFetchCallback.onLocalDataFetched(url, content);
			return content.rssContent;
		}

		// 已经在抓取数据
		if (fetechCache.containsKey(url)) {
			return null;
		} else {
			fetechCache.put(url, url);
		}

		// 开始获取
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					// 获取网络内容
					String content = Utils.fetchData(url);
					// 回调接口
					dataFetchCallback.onDataFetched(url, content);
					// 持久化到数据库
					dbdao.updateRSSContent(content, url);

					imageFetchAndPersistant(content, columnFlagStarter,
							columnFlagEnd, dbdao, url);

					// 将url移出缓存池
					fetechCache.remove(url);
				} catch (IOException e) {
					dataFetchCallback.onError(url, e);
				}
			}
		}).start();

		return null;
	}

	/**
	 * 抓取内容区的图片链接并下载图片到本地
	 * 
	 * @param content
	 * @param columnFlagStarter
	 * @param columnFlagEnd
	 */
	public static final void imageFetchAndPersistant(String content,
			final String columnFlagStarter, final String columnFlagEnd,
			final DBDAO dbdao, final String contentUrl) {
		final String temp = Utils.interceptedContent(content,
				columnFlagStarter, columnFlagEnd);
		new Thread(new Runnable() {

			@Override
			public void run() {
				List<String> imgUrls = ImgFilter.getImageSrc(temp);
				for (final String imgUrl : imgUrls) {
					NetUtil.getInputStream(imgUrl, new NetProcessComplete() {

						@Override
						public void onProcess(InputStream inputStream) {
							String savePath = DrawableUtils
									.getImageSavePath(imgUrl);
							DrawableUtils.saveInputStream2Drawable(savePath,
									imgUrl, inputStream);
							// 保存图片地址到数据库
							dbdao.insertImageByUrl(contentUrl, imgUrl);
						}
					});
				}
			}
		}).start();
	}
}
